package com.java.simple.study.juc.p5;

import java.math.BigDecimal;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author zhoujunlin
 * @date 2022年06月30日 21:18
 * @desc
 */
public class DecimalAccountCas implements DecimalAccount {

    private AtomicReference<BigDecimal> refAccount;

    public DecimalAccountCas(String balance) {
        this.refAccount = new AtomicReference<>(new BigDecimal(balance));
    }

    @Override
    public BigDecimal getBalance() {
        return refAccount.get();
    }

    @Override
    public void withdraw(BigDecimal amount) {
        while (true) {
            BigDecimal prev = refAccount.get();
            BigDecimal next = prev.subtract(amount);
            if (refAccount.compareAndSet(prev, next)) {
                break;
            }
        }
    }

    public static void main(String[] args) {
        DecimalAccount.demo(new DecimalAccountCas("10000"));
        // 剩余:0 cost:134 ms
    }

}
